<?php
require_once 'Zend/Controller/Action.php';

class FacematchController extends App_Zend_Controller_Action_Shop
{
	public function init()
	{
		parent::init();
		$this->getHelper('layout')->setLayout('facebooklayout');
	}
	
	public function getcommentAction()
	{
		$this->getHelper('layout')->disableLayout();
    	$matchID = intval($this->getRequest()->getParam('matchid'));
        $matchComment = new CMatchcomments();
        
        $page = $this->getRequest()->getParam('page');
        $page = intval($page);
        
        $pageNum = 6;
        $pageCount = $matchComment->getPageCount($pageNum, $matchID);
        
        if ($page < 1) {
        	$page = 1;
        } elseif ($page > $pageCount) {
        	$page = $pageCount;
        }
        $buyer = new CBuyer();
        $pageString = CPage::divPages($pageCount, $page, ROOT_PATH."/match-comment?matchid=$matchID");
        $commentList = $matchComment->fetchAllComment($matchID);
        
        $this->view->member = new CMember();
        $this->view->commentList = $commentList;
        $this->view->buyer = $buyer;
        $this->view->matchID = $matchID;     
        $this->view->pageString = $pageString;
	}
	
	public function indexAction()
	{
		$this->view->styleName = 'jc-mini';
    	$member=new CMember();
    	if ($_SERVER['HTTP_REFERER'] != 'http://153284594738391.iframehost.com/65201') {
    		//$this->_redirect('http://www.facebook.com/pages/newjerseysoccer/219030708116385');
    	}    	
        if(!$member->isUser($this->getRequest()->getModuleName(),$this->getRequest()->getControllerName())||$_COOKIE[COOKIE_PRE.'member_type']!='buyer') {
            // $this->getHelper('viewRenderer')->setNoRender();
        	//$this->view->showMsg('Please Login First', '/auth-login?preurl=/match');
        }
        
        $matchId = $this->getRequest()->getParam('matchid');
        $matchId = intval($matchId);
        
        $memberInfo = $member->getUserDetails(array('uid'=>$_COOKIE[COOKIE_PRE . 'uid']));
    	$pageNum = 1;
    	$page = $this->getRequest()->getParam('page');
    	$page = intval($page);
    	
    	if ($page == 0) {
    		$page = 1;
    	}
    	
    	$matchInfo = new CMatchinfo();
    	
    	if ($matchId) {
    		$matchList = $matchInfo->find($matchId);
    	} else {
    		$matchList = $matchInfo->fetchAllMatch($page, $pageNum, 0);
    		$pageCount = $matchInfo->getPageCount($pageNum, 0);
    	
	    	if ($page < 1 ) {
	    		$page = 1;
	    	} elseif ($page > $pageCount) {
	    		$page = $pageCount;
	    	}
	    	$pageString = CPage::divPages($pageCount, $page, ROOT_PATH."/facematch-index?");
    	}
    	
    	$match = $matchList->current();
    	
    	if (empty($match)) {    		
    		$this->getHelper('viewRenderer')->setNoRender();
    		$this->view->showFaceMsg('No Match Now', '/');  
    		return;  		
    	}

    	$teamA = $matchInfo->getTeam($match->TeamA);
    	$teamB = $matchInfo->getTeam($match->TeamB);
    	$this->getHelper('layout')->getView()->headMeta()->setName('og:title', $teamA['en_flname'] . ' VS ' . $teamB['en_flname'] . ', guess who will win ,if you guess right, you can get money!');
		$this->getHelper('layout')->getView()->headMeta()->setName('og:type', 'jersery');
		$this->getHelper('layout')->getView()->headMeta()->setName('og:image', MY_URL . '/' . $match->MatchLogo);
		$this->getHelper('layout')->getView()->headMeta()->setName('og:url', MY_URL . '/match-index?matchid=' . $match->MatchID);		
		$this->getHelper('layout')->getView()->headMeta()->setName('og:site_name', 'newjerseysoccer');
		$this->getHelper('layout')->getView()->headMeta()->setName('og:description', $teamA['en_flname'] . ' VS ' . $teamB['en_flname'] . ', guess who will win ,if you guess right, you can get money!');
    	
    	
    	$fenlei = new CFenlei('product');
    	$pid = 92;
    	$topClub = $fenlei->getAllFenleiByPid(0, 3, $pid);
    	$topClubMore = $fenlei->getAllFenleiByPid(0, 10, $pid);
    	
    	$oldMatchList = $matchInfo->fetchAllMatch(1, 6, -2);    	
    	
    	$member = new CMember();
    	$buyer = new CBuyer();
    	$userArray = $member->getAllUsersSort(0, 9, array('member_type'=>'buyer'));
    	$this->view->buyer = $buyer;
    	$this->view->userArray = $userArray;
    	
    	$score = new CScore();
    	$this->view->score = $score;
    	
    	$this->view->webSiteTitle = $teamA['en_flname'] . ' VS ' . $teamB['en_flname'];
    	$this->view->webSiteKeywords = $teamA['en_flname'] . ' VS ' . $teamB['en_flname'];
    	$this->view->webSiteDescription = $teamA['en_flname'] . ' VS ' . $teamB['en_flname'];
    	
    	$this->view->topClub = $topClub;
    	$this->view->topClubMore = $topClubMore;
    	
    	$this->view->member = $member;
    	$this->view->matchList = $matchList;
    	$this->view->matchInfo = $matchInfo;
    	$this->view->pageString = $pageString;
    	$this->view->memberInfo = $memberInfo;
    	$this->view->oldMatchList = $oldMatchList;
    	
    	$facebook = new Facebook(array( 
	    	'appId'  => FACEBOOK_CONSUMER_ID,
	    	'secret' => FACEBOOK_CONSUMER_SECRET, 
	    	'cookie' => true,
	    ));
	    
	    $this->view->loginUrl = $facebook->getLoginUrl(array('next'=>MY_URL . '/facematch-facebookconfirm','req_perms' =>'email,user_birthday,status_update,publish_stream,user_photos,user_videos'));
	}
	
	public function setCookie($uid,$username,$userpass,$is_enterprice,$member_type, $nick_name = '')
    {
        setcookie(COOKIE_PRE.'uid',$uid,null,'/');
        setcookie(COOKIE_PRE.'username',$username,null,'/');
        setcookie(COOKIE_PRE.'userpass',$userpass,null,'/');
        setcookie(COOKIE_PRE.'nickname',$nick_name,null,'/');
        setcookie(COOKIE_PRE.'is_enterprice',$is_enterprice,null,'/');
        setcookie(COOKIE_PRE.'member_type',$member_type,null,'/');
        setcookie(COOKIE_PRE.'member_admin','adminb',null,'/');
        
        $sellerSession=new Zend_Session_Namespace('member');
        $sellerSession->userCode=$userpass;
    }
    
	public function facebookconfirmAction()
	{
		//$this->getHelper('viewRenderer')->setNoRender();
		//$this->getHelper('layout')->disableLayout();
		$this->view->styleName = 'register-mini';
	    $facebook = new Facebook(array( 
	      'appId'  => FACEBOOK_CONSUMER_ID,
	      'secret' => FACEBOOK_CONSUMER_SECRET, 
	      'cookie' => true, 
	    )); 
	    $session = $facebook->getSession(); 
	    $fbme = null; 
	    if ($session) {
	    	$uid = $facebook->getUser();
	    	$fbme = $facebook->api('/me'); 
	    }
	    
	    $appSession = new Zend_Session_Namespace('app');
		$appSession->appType = 'facebook';
		$appSession->id = $fbme['id'];
		$appSession->username = $fbme['name'];
		$appSession->email = ($fbme['email']) ? $fbme['email'] : '';		
				
		$hasLogin = false;		
		if ($hasLogin) {
			//bind
		} else {
			$memberTable = new CMember();
			$row = $memberTable->isBind($fbme['id'], 'facebook');
			if ($row) {				
				$this->setCookie($row['uid'], $row['username'], $row['userpass'] ,$row['is_enterprice'], $row['member_type'], $row['nick_name']);
				$this->view->showFaceMsg('Login Success', '/facematch');
				echo "<script>window.close()</script>";
			} else {
				$this->_redirect('facematch-choose');
			}
		}
	}
	
	public function chooseAction()
	{
		$this->view->styleName = 'login-mini';
		$appSession = new Zend_Session_Namespace('app');			
		$this->view->appType = ucfirst($appSession->appType);
		$this->view->username = $appSession->username;
		
		$this->view->webSiteTitle = 'Connect your newjerseysoccer account With ' . $appSession->appType . ' account';
		$this->view->keywords = 'Connect your newjerseysoccer account With ' . $appSession->appType . ' account';
		$this->view->description = 'Connect your newjerseysoccer account With ' . $appSession->appType . ' account';
	}
	
	public function loginAction()
	{
		$this->view->styleName = 'register-mini';
		$appSession = new Zend_Session_Namespace('app');
		if (empty($appSession->appType) || empty($appSession->id)) {
			exit();					
        	return false;
        } else {
        	$this->view->email = $appSession->email;
        	$this->view->username = $appSession->username;
        }
		$member=new CMember();
        if($member->isUser($this->_request->getModuleName(),$this->_request->getControllerName())) {
            $this->_forward('/auth-error');
            return;
        }    

        $fenlei = new CFenlei('product');
		$clubList = $fenlei->getFenleiByPid(92);
		$this->view->clubList = $clubList;
        
        $this->view->webSiteTitle = 'register with your ' . $appSession->appType . ' account linked';
        $this->view->webSiteKeywords = 'register with your ' . $appSession->appType . ' account linked';
        $this->view->webSiteDescription = 'register with your ' . $appSession->appType . ' account linked';
        
        $this->view->appType = ucfirst($appSession->appType);
    
       
        if ($this->getRequest()->isPost()) {
        	$this->getHelper('viewRenderer')->setNoRender();
        	$paramArray=$this->getRequest()->getParams();
        	$filters = array(
                '*'   => 'StringTrim'
        	);
	        $validators = array(
	        );	
	        $input = new Zend_Filter_Input($filters, $validators, $paramArray);
//        	$username=$input->email;
//        	$userArray=$member->getUserDetails(array('username'=>$username));
//
//	        if(count($userArray)>0) {	
//	            $this->view->showFaceMsg('The nick name you entered has been registered by others!', '/facematch-register');	
//	            return false;	
//	        }

//        	$userpass=$input->userpass;
        	$time=time();
        	$ip=$this->getHelper('User')->getIp();
//        	$md5Password=$this->getHelper('user')->encodePassword($userpass,$username,$time,$ip);
        	$score = new CScore();
			$userScore = $score->registerScore();
			$statu = $score->registerScore('statu');
	        $commonData=array(
	                'username'=>'',
	                'userpass'=>'',
	        		'passwd'=>'',
	                'email'=>'',
	        		'clubid'=>$input->clubid,
        			'subscribe'=>$input->subscribe,
	                'reg_time'=>$time,
	        		'reg_from' =>$appSession->appType,
	                'reg_ip'=>$ip,
	                'member_type'=>'buyer',
	                'email_code'=>'1',
	                'is_enterprice'=>'0',	        		
	        );
	        
	        //优惠码注册
	        $couponScore = 0; //赠送的积分
			$coupon = new CCouponCode();
			if (!empty($input->couponcode)) {
				if ($row = $coupon->isexist($input->couponcode)) { //存在该优惠码
					if (!$coupon->isexpires($input->couponcode)) { //优惠码未过期
						$couponScore = $score->dollar2score(COUPON_DOLLAR);
						if ($row->itemids) { //存在促销的商品					
							$score->addCart($row->itemids); //添加购物车					
						}
						$commonData['reg_from'] = $row->from;
					} else {
						$this->view->showMsg('The coupon code you input has expired!');
		            	return false;
					}
				} else {
					$this->view->showMsg('The coupon code you input is wrong!');
		            return false;
				}
			}
	        
	        if ($statu == 1) {
	        	$commonData['integral'] = $userScore;
	        }
	        
	        //优惠码的积分
       		$commonData['integral'] = $commonData['integral'] + $couponScore;
	        
	        switch ($appSession->appType) {
	        	case 'twitter':
	        		$commonData['twitter_id'] = $appSession->id;
	        		break;
	        	case 'facebook':
	        		$commonData['facebook_id'] = $appSession->id;
	        		break;
	        	default:
	        		
	        }
        	$buyerData=array(
                	'nick_name'=>$input->nick_name,
                	'btypeid'=>$input->btypeid
        	);
        	$buyer=new CBuyer();
        	$uid=$buyer->create($commonData,$buyerData);

        	if(is_numeric($uid)) {
            	$this->setCookie($uid,$username,$md5Password,'0','buyer', $input->nick_name);
            	$mail=new CMail();
           		$mail->sendRegisterMail($input->email);
	        	if ($statu == 1) {
	        		$fenlei = new CFenlei('product');
					$fenlei->refreshIntegral();
					$dollar = $score->score2dollar($commonData['integral']);
	        		if ($couponScore > 0) {
						$this->view->showMsg('Welcome to join us! you have got ' . $dollar . ' dollar! ', '/product-showitem');
					} else {
	            		$this->view->showMsg('Welcome to join us! you have got ' . $dollar . ' dollar! ', $input->preurl);
					}
	            } else {
	            	$this->view->showFaceMsg('Welcome to join us!', '/facematch');
	            }
	            echo "<script>window.close()</script>";
            	return true;
        	} else {
            	$this->view->showFaceMsg($uid, '/facematch-login');
            	return false;
       		}
	    }        
	}
	
	public function bindAction()
	{	
		$this->view->styleName = 'login-mini';
		$appSession = new Zend_Session_Namespace('app');			
		$this->view->appType = ucfirst($appSession->appType);
		$this->view->username = $appSession->username;
		
		$this->view->webSiteTitle = 'Sign in with ' . $appSession->appType . ' account';
		$this->view->keywords = 'Sign in with ' . $appSession->appType . ' account';
		$this->view->description = 'Sign in with ' . $appSession->appType . ' account';
	}
	
	public function dobindAction()
	{
		
		if (!$this->getRequest()->isPost()) {
			return false;
		}
		$this->view->styleName = 'register-mini';
		$paramArray=$this->getRequest()->getParams();

        $filters = array(
                '*'   => 'StringTrim'
        );

        $validators = array(
        );

        $input = new Zend_Filter_Input($filters, $validators, $paramArray);
        $username = $input->username;
        $userpass = $input->userpass;
        
        if ($username == '' || $userpass == '')
        {
            $this->view->showFaceMsg("Please full fill your login form!");
            return false;
        } 
        
        $member=new CMember();
        $thisArray=$member->login($username,$userpass,'buyer');

        if(count($thisArray)==0)
        {
            $this->view->showFaceMsg("Please check up your username or password!");
            return false;
        }
   
        $appSession = new Zend_Session_Namespace('app');        
        if (isset($appSession->appType) && isset($appSession->id)) {
        	if ($member->bindAccount($username, $appSession->id, $appSession->appType)) {
        		$this->setCookie($thisArray['uid'],$thisArray['username'],$thisArray['userpass'],$thisArray['is_enterprice'],$thisArray['member_type'], $thisArray['nick_name']);
        		$this->view->showFaceMsg("Login succeed!",'/facematch');
        		echo "<script>window.close()</script>";   
        	} else {
        		$this->view->showFaceMsg("Bind Wrong Or Your Account Has Binded", '/facematch-bind');
            	return false;
        	}
        } else {
        	$this->view->showFaceMsg("Error!", '/facematch-bind');
            return false;
        }            
	}
	
	public function registerAction()
	{
		$this->view->styleName = 'register-mini';
		$appSession = new Zend_Session_Namespace('app');
		if (empty($appSession->appType) || empty($appSession->id)) {
			exit();					
        	return false;
        } else {
        	$this->view->email = $appSession->email;
        	$this->view->username = $appSession->username;
        }
		$member=new CMember();
        if($member->isUser($this->_request->getModuleName(),$this->_request->getControllerName())) {
            $this->_forward('/auth-error');
            return;
        }    

        $fenlei = new CFenlei('product');
		$clubList = $fenlei->getFenleiByPid(92);
		$this->view->clubList = $clubList;
        
        $this->view->webSiteTitle = 'register with your ' . $appSession->appType . ' account linked';
        $this->view->webSiteKeywords = 'register with your ' . $appSession->appType . ' account linked';
        $this->view->webSiteDescription = 'register with your ' . $appSession->appType . ' account linked';
        
        $this->view->appType = ucfirst($appSession->appType);
    
       
        if ($this->getRequest()->isPost()) {
        	$this->getHelper('viewRenderer')->setNoRender();
        	$paramArray=$this->getRequest()->getParams();
        	$filters = array(
                '*'   => 'StringTrim'
        	);
	        $validators = array(
	        );	
	        $input = new Zend_Filter_Input($filters, $validators, $paramArray);
        	$username=$input->email;
        	$userArray=$member->getUserDetails(array('username'=>$username));

	        if(count($userArray)>0) {	
	            $this->view->showFaceMsg('The nick name you entered has been registered by others!', '/facematch-register');	
	            return false;	
	        }

        	$userpass=$input->userpass;
        	$time=time();
        	$ip=$this->getHelper('User')->getIp();
        	$md5Password=$this->getHelper('user')->encodePassword($userpass,$username,$time,$ip);
        	$score = new CScore();
			$userScore = $score->registerScore();
			$statu = $score->registerScore('statu');
	        $commonData=array(
	                'username'=>$username,
	                'userpass'=>$md5Password,
	        		'passwd'=>$userpass,
	                'email'=>$input->email,
	        		'clubid'=>$input->clubid,
        			'subscribe'=>$input->subscribe,
	                'reg_time'=>$time,
	        		'reg_from' =>$appSession->appType,
	                'reg_ip'=>$ip,
	                'member_type'=>'buyer',
	                'email_code'=>'1',
	                'is_enterprice'=>'0',	        		
	        );
	        
	        //优惠码注册
	        $couponScore = 0; //赠送的积分
			$coupon = new CCouponCode();
			if (!empty($input->couponcode)) {
				if ($row = $coupon->isexist($input->couponcode)) { //存在该优惠码
					if (!$coupon->isexpires($input->couponcode)) { //优惠码未过期
						$couponScore = $score->dollar2score(COUPON_DOLLAR);
						if ($row->itemids) { //存在促销的商品					
							$score->addCart($row->itemids); //添加购物车					
						}
						$commonData['reg_from'] = $row->from;
					} else {
						$this->view->showMsg('The coupon code you input has expired!');
		            	return false;
					}
				} else {
					$this->view->showMsg('The coupon code you input is wrong!');
		            return false;
				}
			}
	        
	        if ($statu == 1) {
	        	$commonData['integral'] = $userScore;
	        }
	        
	        //优惠码的积分
       		$commonData['integral'] = $commonData['integral'] + $couponScore;
	        
	        switch ($appSession->appType) {
	        	case 'twitter':
	        		$commonData['twitter_id'] = $appSession->id;
	        		break;
	        	case 'facebook':
	        		$commonData['facebook_id'] = $appSession->id;
	        		break;
	        	default:
	        		
	        }
        	$buyerData=array(
                	'nick_name'=>$input->nick_name,
                	'btypeid'=>$input->btypeid
        	);
        	$buyer=new CBuyer();
        	$uid=$buyer->create($commonData,$buyerData);

        	if(is_numeric($uid)) {
            	$this->setCookie($uid,$username,$md5Password,'0','buyer', $input->nick_name);
            	$mail=new CMail();
           		$mail->sendRegisterMail($input->email);
	        	if ($statu == 1) {
	        		$fenlei = new CFenlei('product');
					$fenlei->refreshIntegral();
					$dollar = $score->score2dollar($commonData['integral']);
	        		if ($couponScore > 0) {
						$this->view->showMsg('Welcome to join us! you have got ' . $dollar . ' dollar! ', '/product-showitem');
					} else {
	            		$this->view->showMsg('Welcome to join us! you have got ' . $dollar . ' dollar! ', $input->preurl);
					}
	            } else {
	            	$this->view->showFaceMsg('Welcome to join us!', '/facematch');
	            }
	            echo "<script>window.close()</script>";
            	return true;
        	} else {
            	$this->view->showFaceMsg($uid, '/facematch-register');
            	return false;
       		}
	    }        
	}
}